<script setup lang="ts">
import CameraCapture from "@/views/PublicCom/cameraCapture.vue";
import Upload from "@/views/PublicCom/ImageFilesUpload.vue";
import {useDataPublicStore} from '@/stores/dataPublicStore.ts';
import {onMounted, ref} from "vue";
import router from "@/router/index.js";
import {ElMessage} from "element-plus";
// import {useMaterialInStore} from "@/stores/materialInStore.ts";
import {useMaterialTypeStore} from "@/stores/materialTypeStore.ts";
import {
  useAddOneAPI,
  useGetFirstLevelAPI,
  useGetSecondLevelAPI,
  useGetSecondLevelByPidAPI
} from "@/apis/warehouseLayout.js";
import {useSaveOneMaterialInFormAPI} from "@/apis/materialIn.js";
import {getProjectListAPI} from "@/apis/projectInfo.js";

const dataPublicStore=useDataPublicStore();
const materialTypeStore=useMaterialTypeStore();




/*======================================================================================*/
// 货架层数代码
interface WarehouseLayout{
  containerNumber:number,
  containerName:string,
  pid:number,
  description:string
}
const firstLevelList=ref<WarehouseLayout[]>([])
const secondLevelList=ref<WarehouseLayout[]>([])
const firstLevel=ref({});
const secondLevel=ref({});
const layoutNum=ref('')

// 定义获取 containerNumber 最大值的函数
const getMaxContainerNumber = (list:[]) => {
  if (list.length === 0) {
    return 0;
  }
  // 遍历 firstLevelList，将 containerNumber 转换为数字并找出最大值
  return Math.max(...list.map(item => Number(item.containerNumber)));
};

const secondLevelFlag=ref(true);

// 添加二级节点
const firstLevelChange=async (val:any)=>{
  secondLevel.value={};
  secondLevelFlag.value=false;
  layoutNum.value=val.containerNumber+"-";
  await useGetSecondLevelByPidAPI(val.id).then(res => {
      secondLevelList.value = res.data
    })
}

const warehouseLayout=ref<WarehouseLayout>({
  containerNumber:0,
  containerName:'',
  pid:0,
  description:''
})


const maxNum=ref(0);


const secondSelectChange=async (val:any)=>{

  layoutNum.value=layoutNum.value+val.containerNumber+"-";
//   获取选择到的二级节点下面的三级节点列表

  await useGetSecondLevelByPidAPI(val.id).then(async res => {

    let thirdList = res.data;


    if (thirdList === null) {
      layoutNum.value = layoutNum.value + "1";
      warehouseLayout.value.containerNumber = maxNum.value+1;
      warehouseLayout.value.containerName = materialName.value;
      warehouseLayout.value.pid = val.id;

    } else {

      // 这段代码有问题*********************************************************

      maxNum.value = getMaxContainerNumber(thirdList) + 1;

      layoutNum.value = layoutNum.value + maxNum.value.toString();

      warehouseLayout.value.containerNumber = maxNum.value;
      warehouseLayout.value.containerName = materialName.value;
      warehouseLayout.value.pid = val.id;
    }
  })
}

const receiveFromProjectList=ref([]);
const receiveFromProject=ref({})

/*===================================================*/

onMounted( async ()=>{
  // 获取全部材料类别列表
  await materialTypeStore.getFullMaterialType(1,100000);

  // 货架层级数据
  await useGetFirstLevelAPI().then(res => {
    firstLevelList.value = res.data
  })
  await useGetSecondLevelAPI().then(res => {
    secondLevelList.value = res.data
  })

  await getProjectListAPI(1,100000).then(res=>{
    receiveFromProjectList.value=res.data;
  })

})

// 显示进度条配合函数
const format=(percentage:number)=>{
  return percentage===100?'100%':`${percentage}`
}
const disableSwitch=ref(false);
const materialName=ref('');
const materialBrand=ref('');
const materialNumber=ref(0);
const materialDescription=ref('');
const materialPieces=ref('');
const materialModel=ref('');


// 根据全设备类型名称查询
const typeValueList=ref([])
const typeFullName=ref('')


const getMaterialByTypeName= ()=>{
  if(typeValueList.value===undefined){
   typeFullName.value=''
  }else{
    typeFullName.value=typeValueList.value[0]+':'+typeValueList.value[1];
  }
}


const  submitSaveOneTransfer=async ()=>{

  console.log(receiveFromProject.value);

  if (materialNumber.value<=0){
    ElMessage({
      type:"warning",
      message:'数量不能小于等于0！'
    })
    return;
  }
  const formData=new FormData();
  formData.append('materialName',materialName.value);
  formData.append('brand',materialBrand.value);
  formData.append('description',materialDescription.value);
  formData.append('number',materialNumber.value);
  formData.append('pieces',materialPieces.value);
  formData.append('model',materialModel.value);
  formData.append('typeName',typeFullName.value);
  formData.append('layout',layoutNum.value);
  formData.append('price',price.value);
  formData.append('totalPrice',totalPrice.value);
  formData.append('receiveProject',receiveFromProject.value.name);
  if (dataPublicStore.photoFileList.length>0){
    dataPublicStore.photoFileList.forEach((item:File)=>{
      formData.append('photoFiles',item);
    })
  }
  if (dataPublicStore.uploadFileList.length>0){
    dataPublicStore.uploadFileList.forEach((item:File)=>{
      formData.append('photoFiles',item);
    })
  }



  await useSaveOneMaterialInFormAPI(formData);
  await useAddOneAPI(warehouseLayout.value);

  disableSwitch.value=true;
  dataPublicStore.setPhotoFiles([]);
  dataPublicStore.setUploadFileList([]);
  dataPublicStore.setOnUploadProgress(0);
  dataPublicStore.saveDataObject({});
   await router.push({path: '/home/material'})
}

const gotoAddWarehouseLayout=()=>{
  const routerUrl=router.resolve({
    path:'/home/material/warehouseLayoutManage',
    query:{
      keyWord:keyWord.value
    }
  })
  window.open(routerUrl.href,'_blank')
}

const keyWord=ref(null);
const gotoAddMaterialType=()=>{

  const routerUrl=router.resolve({
    path:'/home/material/materialTypeManage',
    query:{
      keyWord:keyWord.value
    }
  })
  window.open(routerUrl.href,'_blank')

}

const price=ref(0);
const totalPrice=ref(0);
const getTotalPrice=()=>{
  totalPrice.value=Math.round(price.value*materialNumber.value*100)/100;
}




</script>

<template>
  <!--  进度条-->
  <el-progress :percentage="dataPublicStore.onUploadProgress" :format="format"    :stroke-width="5" v-show="dataPublicStore.onUploadProgress" style="margin: 0;padding: 0" ></el-progress>
  <!-- 面包屑 -->
  <div class="bread-container">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: `/` }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:`/home/material/`}" >材料列表</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:`/home/material/materialInList`}" >材料进场列表</el-breadcrumb-item>
      <el-breadcrumb-item  >材料进场详情</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <div class="divTable">
    <table class="table">
      <tbody>
      <tr>
        <td class="tableTitle" colspan="4" >新材料进场表</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF;color: #242424;font-family: 微软雅黑,serif">材料名称</td>
        <td style="width: 350px;height: 15px;   text-align: center  "><el-input  v-model="materialName" /></td>
        <td style="width: 250px;height: 15px; text-align: center ;background: #EFF6FF"  >材料品牌</td>
        <td style="width: 350px;height: 15px;   text-align: center  "><el-input  v-model="materialBrand" /></td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">
          <el-tooltip placement="top">
            <template #content> <el-button type="text" @click="gotoAddMaterialType">
              没有对应的类型？请添加！
            </el-button></template>
            材料类型
          </el-tooltip>


        </td>
        <td style="width: 350px;height: 15px;text-align: center;">
          <el-cascader
              placeholder="请选择材料类型"
              :options="materialTypeStore.fullMaterialType"
              filterable
              v-model="typeValueList"
              @change="getMaterialByTypeName"
              clearable
              style="margin-right: 20px;width: 100%"
          />
        </td>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">
          材料型号
        </td>
        <td style="width: 350px;height: 15px;text-align: center;"><el-input  v-model="materialModel" /></td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">材料数量单位</td>

        <td style="width: 250px;height: 15px;text-align: center;"><el-input  v-model="materialPieces" /></td>

        <td   style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >材料进场数量</td>

        <td  style="width: 250px;height: 15px;text-align: center   ">
          <el-input  v-model="materialNumber" />
        </td>
      </tr>

      <tr>
        <td   style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >
          <el-tooltip placement="top">
            <template #content> <h3>
              如实填写购买的单价
            </h3>
            </template>
            材料单价
          </el-tooltip>

        </td>
        <td  style="width: 350px;height: 15px;text-align: center   ">
          <el-input @change="getTotalPrice" v-model="price" />
        </td>
        <td   style="width: 150px;height: 15px;text-align: center ;background: #EFF6FF"  >材料总价</td>
        <td  style="width: 150px;height: 15px;text-align: center   ">
          <el-input disabled  v-model="totalPrice" />
        </td>
      </tr>


<!--      选择货架  -->
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">
          <el-tooltip placement="top">
            <template #content> <el-button type="text" @click="gotoAddWarehouseLayout">
              没有对应的货架？请添加！
            </el-button></template>
            第一层货架
          </el-tooltip>
        </td>
        <td>
          <el-select
              value-key="id"
              v-model="firstLevel"
              placeholder="Select"
              size="large"
              @change="firstLevelChange"
          >
            <el-option
                v-for="item in firstLevelList"
                :key="item.id"
                :label="item.containerName"
                :value="item"
            />
          </el-select>
        </td>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">

          <el-tooltip placement="top"
                      :disabled="secondLevelFlag"
          >
            <template #content> <el-button type="text" @click="gotoAddWarehouseLayout">
              没有对应的货架？请添加！
            </el-button></template>
            第二层货架
          </el-tooltip>
        </td>
        <td>
          <el-select
              :disabled="secondLevelFlag"
              value-key="id"
              v-model="secondLevel"
              placeholder="Select"
              size="large"
              @change="secondSelectChange"
          >
            <el-option
                v-for="item in secondLevelList"
                :key="item.id"
                :label="item.containerName"
                :value="item"
            />
          </el-select>
        </td>
      </tr>

      <tr>
        <td  style="text-align: center;background: #EFF6FF">材料来源地</td>
        <td  style="text-align: center">
          <el-select
              value-key="id"
              v-model="receiveFromProject"
              placeholder="Select"
              size="large"
          >
            <el-option
                v-for="item in receiveFromProjectList"
                :key="item.id"
                :label="item.name"
                :value="item"
            />
          </el-select>
        </td>

        <td  style="text-align: center;background: #EFF6FF">备注</td>
        <td  style="text-align: center">
          <el-input  v-model="materialDescription" />
        </td>
      </tr>
      <tr>
        <td colspan="4" style="width: 250px;height: 15px;text-align: center;background: #EFF6FF"></td>
      </tr>
      <tr>
        <td colspan="4">
          <camera-capture/>
        </td>
      </tr>
      <tr>
        <td colspan="4">
          <upload/>
        </td>
      </tr>
      <tr>
        <td colspan="4" style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">
          <el-button
              type="success"
              size="large"
              @click="submitSaveOneTransfer"
          >
            确定
          </el-button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>


</template>

<style scoped lang="scss">
.bread-container {
  padding: 25px 10px;
  margin-left: 10px;
}
.divTable {
  position: absolute;
  top: 150px;
  bottom: 0;
  left: 300px;
  right: 0;
  margin: auto;
}


table, td,tr{
  border: 1px solid #44a8da;
  text-align: center;
  border-spacing: 0;
  border-collapse: collapse;
  height: 45px;
}

.tableTitle{

  border-right: 0 none;
  border-left: 0 none;
  text-align: center;
  font-size: large;
  font-weight: bold;
}

.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

</style>